package com.chensi.admin.web.util;

import com.chensi.admin.web.common.Constants;
import com.chensi.admin.web.exception.BaseException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Optional;

import static com.chensi.admin.web.common.BaseErrorCode.*;
import static com.chensi.admin.web.common.Constants.LOGIN_ERROR_TIME_SCOPE;

/**
 * @Author: si.chen
 * @Date: 2019/6/18 9:56
 */
@Component
public class ValidationUtil {

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 检验非空
     */
    public static void isNull(Optional optional, String entity, String parameter, Object value) throws BaseException {
        if (!optional.isPresent()) {
            String msg = entity
                    + " 不存在 "
                    + "{ " + parameter + ":" + value.toString() + " }";
            throw new BaseException(ITEM_NOT_FOUND, msg);
        }
    }

    /**
     * 验证是否为邮箱
     */
    public static boolean isEmail(String string) {
        if (string == null) {
            return false;
        }
        String regEx1 = "^([a-z0-9A-Z]+[-|.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        return string.matches(regEx1);
    }

    /**
     * 检验密码强度:由数字和字母组成，并且要同时含有数字和字母，且长度要在8-16位之间
     */
    public static boolean isPassword(String string) {
        if (string == null) {
            return false;
        }
        String regEx1 = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,16}$";
        return string.matches(regEx1);
    }


    /**
     * 断言--验证密码
     */
    public void AssertPassword(String username, String realPassword, String password) throws BaseException {
        //校验密码&密码次数上限
        if (!StringUtils.equals(realPassword, password)) {
            //redis key规范==>user:xxx:errorCount
            String key = "user:" + username + ":errorCount";
            Object num = redisUtil.get(key);
            if (num == null) {
                redisUtil.set(key, 1, LOGIN_ERROR_TIME_SCOPE);
            } else if ((int) num < Constants.LOGIN_ERROR_LIMIT) {
                redisUtil.incr(key, 1);
            } else {
                throw new BaseException(LOGIN_FAIL_TOO_MUCH);
            }
            throw new BaseException(ERROR_PASSWORD);
        }
    }

}
